package com.maxatime.thread;

import java.util.concurrent.locks.ReentrantLock;

/**
 * @author Mr.Zhao
 * @title:
 * @projectName phoenix
 * @description: TODO
 * @date 2021/8/23 19:30
 */
public class ThreadAccount implements Runnable{

    private BankAccount account = new BankAccount();
    ReentrantLock reen = new ReentrantLock();

    @Override
    public void run() {
        for (int i = 0; i < 5; i++) { // 总共取款5次
            makeWithdraw(100); // 每次取款100
            if (account.getBanlance() < 0) {
                System.out.println("☆" + Thread.currentThread().getName() + "   透支了!");
            }
        }
    }

    /**
     * makeWithdraw 账户取款
     *
     * @param amount 取款金额<br />
     *               打印log记录取款过程
     */
     private synchronized void makeWithdraw(int amount){
//    private void makeWithdraw(int amount) {
//        reen.lock();
        if (account.getBanlance() >= amount) { // 如果余额足够则取款
            System.out.println("☆" + Thread.currentThread().getName() + "   准备取款!");
            try {
                Thread.sleep(500);
            } catch (InterruptedException e) {
                System.out.println(Thread.currentThread().getName() + "   准备取款,等待0.5s线程中断!" + e.getMessage());
            }
            account.withdraw(amount);
            System.out.println(
                    "☆" + Thread.currentThread().getName() + "   完成" + amount + "取款!余额为" + account.getBanlance());
        } else { // 余额不足则提示
            System.out.println(
                    "☆" + "余额不足以支付" + Thread.currentThread().getName() + amount + "   的取款,余额为" + account.getBanlance());
        }
//        reen.unlock();
    }
}
